<?php
/**
 * Mailview
 * http://code.google.com/p/mailview/
 * Martin Tournoij <martin@arp242.net>
 * Mailview is free for any use, there are no restrictions.
 */

include('mailview2.php');
$mailview = new Mailview2();

$vars = array(
	'headers' => '',
	'body' => '',
);

$link = Mailview\imap_open($_SESSION['config']);

# Reply
if (isset($_GET['reply']))
{
	$_GET['uid'] = $_GET['reply'];

	# Setup header field
	$header = Mailview\imap_fetchheader($link, (int) $_GET['reply']);

	if (isset($header['reply-to']))
		$reply = $header['reply-to'];
	else
		$reply = $header['from'];

	if (isset($_GET['all']))
	{
		$reply .= ', ' . $header['from'];

		if (isset($header['cc']))
			$reply .= ', ' . $header['cc'];
	}

	if (strtolower(substr($header['subject'], 0, 3)) === 're:')
		$subject = $header['subject'];
	else
		$subject = 'Re: ' . $header['subject'];

	if (isset($header['message-id']))
		$vars['headers'] .= "In-Reply-To: {$header['message-id']}\n";
	if (isset($_SESSION['config']['mail']))
		$vars['from'] = sprintf('"%s" <%s>', $_SESSION['config']['name'], $_SESSION['config']['mail']);
	else
		$vars['from'] = sprintf('%s@%s', $_SESSION['config']['username'], $_SESSION['hostname']);
	$vars['to'] = $reply;
	$vars['subject'] = $subject;
}
# Brand new message
else
{
	$mymail = '';

	# XXX Set mail and name when reading config
	if (isset($_SESSION['config']['mail']))
		$vars['from'] = sprintf('"%s" <%s>', $_SESSION['config']['name'], $_SESSION['config']['mail']);
	else
		$vars['from'] = sprintf('%s@%s', $_SESSION['config']['username'], $_SESSION['hostname']);
}

# Get body for quote
if (isset($_GET['reply']))
{
	# XXX this is acopy from viewmail.php, make a function out of this
	$struct = Mailview\imap_fetchstructure($link, (int) $_GET['reply']);

	# Multipart
	if ($struct->type === 1)
		$parts = Mailview\MailParts($struct);
	else
	{
		$parts = array('1' => $struct);
		$parts['1']->partno = 1;
	}

	foreach ($parts as $p)
	{
		# Text
		if ($p->type === 0 or $p->type === 2)
		{
			if ((isset($p->disposition) and $p->disposition === 'attachment') or strtolower($p->subtype) != 'plain' )
				continue;
			else
				$vars['body'] .= Mailview\MailText($link, $p, False);
		}
	}

	$vars['body'] = preg_replace("/(.*)\n/", "> $1\n", $vars['body']);
	$vars['body'] = htmlentities("On {$header['date']} {$header['from']} wrote:\n") . htmlentities($vars['body']) . "\n\n";
}

# Add signature
if ($_SESSION['config']['signature'] != '')
{
	if (file_exists($_SESSION['config']['signature']))
		$vars['body'] .= "\n\n-- \n" . file_get_contents($_SESSION['config']['signature']);
}

$mailview->Template($vars, $link);
?>
